<template>
  <el-menu
    default-active="0"
    class="el-menu-demo"
    mode="horizontal"
    @select="handleSelect"
    background-color="#F2F6FC"
    text-color="#303133">
    <el-submenu index="1">
      <template slot="title">
        <span><img :src="user.avatar" class="avatar" :onerror="defaultTimg"></span>
        <span>{{getNick(user.nick,user.name)+'('+user.name+')'}}</span>
      </template>
      <el-menu-item index="1-1"><i class="el-icon-info"></i>个人资料</el-menu-item>
      <el-menu-item index="1-2">
        <el-popover
          placement="top"
          width="160"
          :visible-arrow="false"
          v-model="roleSelectShow">
          <p>选择角色：</p>
          <el-select v-model="currentRole.name" placeholder="请选择" @change="roleChange">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
          <div slot="reference">
            <i class="el-icon-service"></i>切换角色 ({{currentRole.name}})
          </div>
        </el-popover>
      </el-menu-item>
      <div class="split-line"></div>
      <el-menu-item index="1-3">
        <i class="el-icon-news"></i>
        退出登录
      </el-menu-item>
    </el-submenu>
    <el-submenu index="2">
      <template slot="title">
        <span>语言</span>
      </template>
      <el-menu-item index="2-cn">中文</el-menu-item>
      <el-menu-item index="2-en">英文</el-menu-item>
    </el-submenu>
  </el-menu>
</template>

<script>

  import util from "../utils/util"
  import {User, Role} from '../utils/resource'
  import {mapState, mapActions} from 'vuex'
  import {getMenus} from '../utils/element-helper'


  export default {
    name: "Header",
    data() {
      return {
        activeIndex: '1',
        roles: [],
        currentRole: {},
        roleSelectShow: false,
        user: {},
        defaultTimg: 'this.src="' + require('../assets/timg.png') + '"'
      }
    },
    created() {
      this.loadUser()
      //TODO:可以合并到一个请求
      if (this.user.roleId == -1) {
        this.currentRole = {
          name: "超级管理员"
        }
        this.roles = Object.assign([], this.currentRole)
      } else {
        Promise.all([this.loadCurrentRole(), this.loadUserRole()]).then(value => {
          console.log(value)
        })
      }
    },
    computed: {
      // user() {
      //   let user = sessionStorage.getItem("user")
      //   return JSON.parse(user)
      // }
    },
    methods: {
      changeLang(lang) {
        this.$i18n.locale = lang.split('-')[1]
      },
      async loadCurrentRole() {
        let res = await Role.getCurrentRole()
        this.currentRole = res.data.data
      },
      async loadUserRole() {
        let res = await Role.userRole(this.user.name)
        this.roles = res.data
      },
      async handleSelect(key, keyPath) {
        console.log(key, keyPath)
        if (keyPath[0] === '2') {
          this.changeLang(keyPath[1])
          return
        }
        if (key === "1-1") {
          this.profile()
        } else if (key === "1-3") {
          this.logout()
        }
      },
      async roleChange(data) {
        this.$emit('toggleMainLoading')
        let res = await Role.setCurrentRole(data)
        if (res.data.success) {
          this.roleSelectShow = false
          this.currentRole = res.data.data
          let menus = await getMenus()
          this.setMenus(menus)
        }
        this.$emit('toggleMainLoading')
      },
      async logout() {
        await User.logout()
        sessionStorage.clear()
        this.$router.push({path: "/login"})
      },
      getNick(nick, name) {
        return util.isNull(nick) ? name : nick
      },
      profile() {
        this.$router.push({path: "/user/profile"})
      },
      ...mapActions("menu", [
        "setMenus"
      ]),
      loadUser() {
        let user = sessionStorage.getItem("user")
        this.user = JSON.parse(user)
        if (this.user.avatar === '' || this.user.avatar == null) {
          this.user.avatar = require('../assets/timg.png')
        }
      }
    }
  }
</script>

<style scoped>
  .el-menu-demo {
    border: 0px solid #DCDFE6;
    border-bottom: 2px solid #DCDFE6;
  }

  .el-menu-demo li {
    float: right;
  }

  .split-line {
    border-bottom: 1px solid #DCDFE6;
  }

  .role-desc {
    border-bottom: 1px solid #DCDFE6;
    color: #606266;
    padding: 5px 0 10px 10px;
    font-size: 13px;
  }

  .avatar {
    height: 40px;
    width: 40px;
    border-radius: 20px;
    border: 2px solid #DCDFE6;
  }
</style>
